package mumu.android.monitoring;

import java.util.List;
import java.util.Timer;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import android.app.ActivityManager;
import android.app.Service;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

/**
 * 进行数据同步处理，版本更新，数据同步
 * 
 * @author Administrator
 * 
 */
public class AppService extends Service {

	Timer timer;
	public ScheduledExecutorService scheduExecSingle;

	@Override
	public void onStart(Intent intent, int startId) {
		super.onStart(intent, startId);
	}

	@Override
	public void onCreate() {
		super.onCreate();
		scheduExecSingle = Executors.newScheduledThreadPool(2);
		// 首次延迟20秒，后每一个小时执行一次
		// scheduleWithFixedDelay从字面意义上可以理解为就是以固定延迟（时间）来执行线程任务，它实际上是不管线程任务的执行时间的，每次都要把任务执行完成后再延迟固定时间后再执行下一次。
		// 而scheduleFixedRate呢，是以固定频率来执行线程任务，固定频率的含义就是可能设定的固定时间不足以完成线程任务，但是它不管，达到设定的延迟时间了就要执行下一次了。
		scheduExecSingle.scheduleWithFixedDelay(GetAppRunnable(), 1, 2, TimeUnit.SECONDS);

	}

	Runnable GetAppRunnable() {
		return new Runnable() {

			@Override
			public void run() {
				ActivityManager activityManager = (ActivityManager) getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
				ComponentName topActivity = activityManager.getRunningTasks(1).get(0).topActivity;
				String packageName = topActivity.getPackageName();
				String className = topActivity.getClassName();
				Log.v("dd", "packageName----" + packageName);
				Log.v("dd", "className----" + className);

				isAppOnForeground(AppService.this);
			}
		};
	}

	/**
	 * 程序是否在前台运行
	 * 
	 * @return false 在后台
	 */
	public static boolean isAppOnForeground(Context mContext) {
		// Returns a list of application processes that are running on the
		// device

		ActivityManager activityManager = (ActivityManager) mContext.getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
		String packageName = mContext.getApplicationContext().getPackageName();

		List<RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
		if (appProcesses == null)
			return false;

		for (RunningAppProcessInfo appProcess : appProcesses) {
			// The name of the process that this object is associated with.
			if (appProcess.processName.equals(packageName) && appProcess.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
				return true;
			}
		}

		return false;
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
	}

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

}
